package net.hancl.modules.sys.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FormsAuthenticationFilter extends FormAuthenticationFilter {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    String successUrl = "/";

    @Override
    public void setSuccessUrl(String successUrl) {
        this.successUrl = successUrl;
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new UsernamePasswordToken(username, password, rememberMe, host);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        issueSuccessRedirect(request, response);
        System.out.println("登陆成功");
        logger.debug("登陆成功！");

        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String className = e.getClass().getName();
        request.setAttribute(getFailureKeyAttribute(), className);
        String message = "";
        if(IncorrectCredentialsException.class.getName().equals(className) || UnknownAccountException.class.getName().equals(className)){
            message = "用户或密码错误!";
        } else if (e.getMessage() != null && e.getMessage().startsWith("msg:")) {
            // message = e.getMessage().replace("msg:", "");
        } else {
            message = "登陆异常！";
            logger.debug("登陆异常！");
            e.printStackTrace();
        }
        // getFailureKeyAttribute
        request.setAttribute("shiroLoginFailure", className);
        request.setAttribute("message", message);

        return true;
    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.redirectToSavedRequest(request, response, successUrl);
    }
}
